<template>
  <div class="fill-in-blanks-question">
    <div class="question-result" v-if="showAnswerResult">
      <img :src="correctImg" alt="" v-if="answerRight()" />
      <img :src="errorImg" alt="" v-else />
    </div>
    <div>
      <Checkbox
        v-if="showChecked"
        label=""
        @on-change="handleSelect($event, question)"
        v-model="question._checked"
        :disabled="getDisabled(question)"
      ></Checkbox>
      <span class="question-no" style="margin-right:0px">{{ index + 1 }}、</span>
      <span
        class="question-name"
        style="font-size: 14px;"
        v-html="parseDescription(question, index)"
      ></span>
      <span v-if="showScore">({{ question.score }}分)</span>
      <Tag class="question-type" color="blue">{{ question.modeCode | modeFilter }}</Tag>
      <Tag
        color="blue"
        v-for="(point, index) in filterAllPoints(question.typeCode || question.type)"
        :key="index"
        >{{ point }}</Tag
      >
      <Tag class="question-diffculty" color="green" v-if="question.difficulty">{{
        question.difficulty | difficultyFilter
      }}</Tag>
      <Tag v-if="question.visibility" class="question-visibility" color="purple">{{
        question.visibility | filterIsPublic
      }}</Tag>
      <span
        v-if="
          showAnswerResult &&
            showNoAnswer &&
            (!question.userAnswer || question.userAnswer.length === 0)
        "
        class="no-answer"
        >（此题未作答）</span
      >
      <span class="question-action" style="float:right;">
        <slot name="action" v-bind:question="question" v-bind:index="index"> </slot>
      </span>
    </div>
    <div class="answer-wrapper">
      <p v-if="showRightAnswer">
        正确答案：<span class="right-answer">{{ question.answers[0].explanation }}</span>
      </p>
    </div>
    <div v-if="showExplanation" class="question-explanation">
      答案解析：
      <span v-if="question.explanation" v-text="question.explanation"></span>
      <span v-else>暂无解析</span>
    </div>
  </div>
</template>
<script>
import common from './mixin'
// import usally from '@/mixin/usally'
export default {
  name: 'FillInTheBlanksQuestion',
  mixins: [common],
  props: {
    question: {
      type: Object,
      validator(value) {
        //4-填空
        return value.modeCode.toString() === '4' && value.name
      }
    }
  },
  data() {
    return {}
  },
  watch: {
    question() {
      this.init()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init() {
      let _this = this
      let answersInputEles = this.$el.getElementsByClassName('quesBlank')
      for (let i = 0; i < answersInputEles.length; i++) {
        let answerEle = answersInputEles[i]
        if (this.pattern === 'answer') {
          if (this.disabledAnswer) {
            answerEle.setAttribute('readOnly', true)
          }
          let answerBox = document.createDocumentFragment()
          let el = document.createElement('span')
          el.className = `answer-txt-${i}`
          answerBox.appendChild(el)
          _this.$el.appendChild(answerBox)
          if (_this.question.userAnswer && _this.question.userAnswer.length > 0) {
            //有答题填充答案
            let str = ' '
            if (Array.isArray(this.question.userAnswer)) {
              str = this.question.userAnswer[i] || ` `
            } else {
              str = this.question.userAnswer
            }
            answerEle.value = str
            let answerTxtEl = _this.$el.getElementsByClassName(`answer-txt-${i}`)
            answerTxtEl[0].innerText = str
            let current_width = answerTxtEl[0].offsetWidth + 20
            answerEle.style.width = Math.max(40, current_width) + 'px'
          } else {
            let str = ` `
            answerEle.value = str
            let answerTxtEl = this.$el.getElementsByClassName(`answer-txt-${i}`)
            answerTxtEl[0].innerText = str
            answerEle.style.width = '40px'
          }
          answerEle.oninput = function(e) {
            let ele = e.currentTarget
            let str = ele.value
            let answerTxtEl = _this.$el.getElementsByClassName(`answer-txt-${i}`)
            answerTxtEl[0].innerText = str
            let current_width = answerTxtEl[0].offsetWidth + 20
            ele.style.width = Math.max(40, current_width) + 'px'
            _this.question.userAnswer[i] = _this.Trim(ele.value)
          }
          answerEle.onchange = function(e) {
            _this.selectAnswer(_this.question, _this.index, _this.question.userAnswer)
          }
        } else {
          answerEle.setAttribute('readOnly', true)
        }
      }
    },
    selectAnswer(question, index, userAnswer) {
      if (this.pattern === 'answer') {
        this.$emit('handleAnswerSelect', question, index, userAnswer)
      }
    },
    parseDescription(question, index) {
      if (!question.answers) {
        return
      }
      let description = question.name || question.description
      description = description.replace(
        /\{\{.*?\}\}/g,
        `<input class='quesBlank' maxlength="64" style='width:40px;padding:0px 5px;outline:none;box-shadow:none;border:none;border-bottom:1px solid rgb(168,166,200);background: transparent;color: var(--default-color)'></input>`
      )
      let el = document.createElement('div')
      el.innerHTML = description
      return el.innerHTML
    },
    Trim(str, is_global) {
      var result
      result = str.replace(/(^\s+)|(\s+$)/g, '')
      if (is_global && is_global.toLowerCase() == 'g') {
        result = result.replace(/\s/g, '')
      }
      return result
    }
  }
}
</script>
<style scoped src="./question.css"></style>
<style>
.fill-in-blanks-question span[class^='answer-txt'] {
  position: absolute;
  visibility: hidden;
  font-size: 14px;
}
</style>
